﻿using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Hosting;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SignalRServer
{
    public partial class Form1 : Form
    {
        public IDisposable SignalR { get; set; }
        private const string ServerUri = "http://localhost:4008"; // SignalR服务地址
        private delegate void WriteToConsoleDe(string msg);

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            BtnStop.Enabled = false;
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            BtnStart.Enabled = false;
            BtnStop.Enabled = true;

            WriteToConsole("正在启动服务...");
            Task.Run(() => { BtnStart.Enabled = !StartServer(); }); // 异步启动SignalR服务
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            WriteToConsole("服务正在停止...");
            if (SignalR != null)
            {
                SignalR.Dispose();
            }
            BtnStop.Enabled = false;
            BtnStart.Enabled = true;
            WriteToConsole("服务已停止：" + ServerUri);
        }

        private void BtnSend_Click(object sender, EventArgs e)
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessageHub>();
            context.Clients.All.SendMessage(TxtMsg.Text);
        }

        /// <summary>
        /// 启动SignalR服务，将SignalR服务寄宿在WPF程序中
        /// </summary>
        private bool StartServer()
        {
            try
            {
                SignalR = WebApp.Start(ServerUri);  // 启动SignalR服务
            }
            catch (Exception ex)
            {
                WriteToConsole(ex.Message);
                return false;
            }

            WriteToConsole("服务已经成功启动，地址为：" + ServerUri);
            return true;
        }

        /// <summary>
        /// 将消息添加到消息列表中
        /// </summary>
        /// <param name="message"></param>
        public void WriteToConsole(string message)
        {
            if (TxtConsole.InvokeRequired)
            {
                TxtConsole.Invoke(new Action<string>((string msg) => TxtConsole.AppendText(message + Environment.NewLine)), message);
                return;
            }

            TxtConsole.AppendText(message + Environment.NewLine);
        }
    }
}
